# -*- coding: UTF-8 -*-
"""
@File ：product_product
@Author ：lucas
@Date ：2023-10-18 23:04:24
@Description: 
"""

import logging
from odoo import api, fields, models, tools

_logger = logging.getLogger(__name__)

PRODUCT_TYPES = [('service', '服务'), ('consume', '消耗品'), ('product', '库存商品')]


class ProductProduct(models.Model):
    _name = 'justdoo.product.product'
    _description = '产品信息'
    _rec_name = 'code'
    _order = 'id desc'
    _inherit = ['mail.thread', 'mail.activity.mixin']

    @tools.ormcache()
    def _get_default_category_id(self):
        return self.env.ref('justdoo_product.product_category_all')

    name = fields.Char('名称', required=True, index=True)
    code = fields.Char('编码', required=True, index=True, tracking=True)
    active = fields.Boolean('启用', default=True, tracking=True)
    barcode = fields.Char(string='Barcode')
    specification = fields.Char(string='规格型号')
    description = fields.Html('描述信息')
    product_image = fields.Image('产品图片')
    stock_age = fields.Integer(string='库龄(月)', default=0, tracking=True)
    enable_lot = fields.Boolean('启用批次', default=False, tracking=True)
    product_type = fields.Selection(PRODUCT_TYPES, '产品类型', default='product')
    uom_id = fields.Many2one('justdoo.product.uom', '单位', required=True, ondelete='restrict')
    uom_name = fields.Char('产品单位', compute='_compute_product_uom', store=True)
    product_category_id = fields.Many2one('justdoo.product.category', '产品分类',
                                          default=_get_default_category_id, required=True)
    operate_time = fields.Datetime(string='操作时间', default=fields.Datetime.now)
    operator_id = fields.Integer('维护员ID', default=lambda self: self.env.user.id)
    operator_name = fields.Char('维护员', default=lambda self: self.env.user.name)
    company_name = fields.Char('公司', default=lambda self: self.env.company.name)
    company_id = fields.Integer('公司ID', default=lambda self: self.env.company.id)
    uom_category_id = fields.Many2one('justdoo.uom.category', '单位分类', compute='_compute_product_uom', store=True)

    _sql_constraints = [('uniq_code', 'unique (code)', '编码已存在请不要重复添加!')]

    @api.depends('uom_id')
    def _compute_product_uom(self):
        for record in self:
            record.uom_name = False if not record.uom_id else record.uom_id.name
            record.uom_category_id = False if not record.uom_id else record.uom_id.category_id

    def write(self, values):
        values.update({
            'operate_time': fields.Datetime.now(),
            'operator_id': self.env.user.id, 'operator_name': self.env.user.name
        })
        return super().write(values)


